﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DeliveryPlus.Web.Controllers;
using DeliveryPlus.Web.DAL.Entities;

namespace DeliveryPlus.Web.Areas.ControlPanel.Controllers
{
    /// <summary>
    /// Контроллер управления списком кафе
    /// </summary>
    public class ManageCafeController : BaseController
    {
        /// <summary>
        /// Список кафешек в системе
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            var cafe = DataContext.Cafes.OrderBy(c => c.Title).ToList();
            return View(cafe);
        }

        /// <summary>
        /// Отображает форму создания новой кафешки
        /// </summary>
        /// <returns></returns>
        public ActionResult Add()
        {
            return View("EditCafe", new Cafe());
        }

        /// <summary>
        /// Отображает форму редактирования кафе
        /// </summary>
        /// <param name="id">Идентификатор кафе</param>
        /// <returns></returns>
        public ActionResult Edit(long id)
        {
            var cafe = DataContext.Cafes.FirstOrDefault(c => c.Id == id);
            if (cafe == null)
            {
                return RedirectToAction("Index");
            }

            return View("EditCafe", cafe);
        }

        /// <summary>
        /// Обрабатывает сохранение указанного кафе
        /// </summary>
        /// <param name="model">Модель</param>
        /// <param name="logoFile">Файл с логотипом</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Save(Cafe model, FormCollection collection)
        {
            // Сохраняем файл
            var logoFile = Request.Files["logoFile"];
            var logoFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Files", "Logo",Path.GetRandomFileName());
            logoFilePath = Path.ChangeExtension(logoFilePath, ".jpg");
            string logofileName = null;
            if (logoFile != null && logoFile.ContentLength > 0 && logoFile.ContentType.Contains("image"))
            {
                logoFile.SaveAs(logoFilePath);
                logofileName = Path.GetFileName(logoFilePath);
            }

            var types = String.Join(",",
                collection.AllKeys.Where(k => k.StartsWith("types-")).Select(k => k.Split('-')[1]));

            if (model.Id <= 0)
            {
                model.DateCreated = DateTime.Now;
                model.Logo = logofileName;
                model.Types = types;
                DataContext.Cafes.InsertOnSubmit(model);
                DataContext.SubmitChanges();
            }
            else
            {
                var cafe = DataContext.Cafes.FirstOrDefault(c => c.Id == model.Id);
                if (cafe == null)
                {
                    return RedirectToAction("Index");
                }

                cafe.Title = model.Title;
                cafe.Address = model.Address;
                cafe.Description = model.Description;
                cafe.Hidden = model.Hidden;
                cafe.Types = types;
                cafe.Logo = logofileName ?? cafe.Logo;
                cafe.DateModified = DateTime.Now;
                if (model.DistrictId != cafe.DistrictId)
                {
                    if (cafe.District != null)
                    {
                        cafe.District.Cafes.Remove(cafe);
                    }
                    if (model.DistrictId != -1)
                    {
                        DataContext.Districts.First(c => c.Id == model.DistrictId).Cafes.Add(cafe);
                    }
                    else
                    {
                        cafe.District = null;
                    }
                }

                DataContext.SubmitChanges();
            }

            return RedirectToAction("Index");
        }

        /// <summary>
        /// Обрабатывает удаление указанной кафешки
        /// </summary>
        /// <param name="id">Идентификатор кафе</param>
        /// <returns></returns>
        public ActionResult Delete(long id)
        {
            var cafe = DataContext.Cafes.FirstOrDefault(c => c.Id == id);
            if (cafe == null)
            {
                return RedirectToAction("Index");
            }

            DataContext.Cafes.DeleteOnSubmit(cafe);
            DataContext.SubmitChanges();

            return RedirectToAction("Index");
        }

    }
}
